package com;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class EncordingAwareSourceViewer {

    public static void main(String[] args) {

        if(args.length > 0){

            try {
                String encoding = "UTF-8";

                URL url = new URL(args[0]);

                URLConnection urlConnection = url.openConnection();

                String contentType = urlConnection.getContentType();

                //System.out.println(contentType);

                //System.out.println(urlConnection.getContentLength());

                int tag = contentType.indexOf("charset=");

                if(tag != -1){

                    encoding = contentType.substring(tag+8);

                    System.out.println("使用编码:" + encoding);

                }

                InputStream in = new BufferedInputStream(urlConnection.getInputStream());

                Reader reader = new InputStreamReader(in,encoding);

                int c;

                while ((c = reader.read()) != -1){
                    System.out.print((char)c);
                }

                reader.close();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

}
